package teamCservlets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;


public class DisplayHomePageServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/* This servlet performs one function, which is to retrieve a list of
		 * open defects from the database and display them on the homepage
		 */

		// Make sure a user is logged in, and if not, redirect to the login page
		PersonBean	authUser = null;
		HttpSession session = request.getSession();
		authUser = (PersonBean) session.getAttribute("user");
		if ((authUser == null) || (authUser.getId() == -1)) {
			response.sendRedirect("login.jsp");
		}

		String 		nextPage = null;
		DatabaseInterfaceDefect		dbDefect = new DatabaseInterfaceDefect();
		ArrayList<DefectBean>		defectList = null;

        // Query the database for the list of open defects.
		defectList = dbDefect.getOpenDefectList();

		if (defectList == null) {

			// TODO - Handle the case that no list is returned, for example, a
			// database access error, or an empty table. Probably want to re-display the login
			// with an error message.

			// For now, just build a page displaying an error message.
			/*response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Team C Defect System</title>");
			out.println("</head>");
			out.println("<body>");
			out.println("<p>In DisplayHomePageServlet.doPost, error retrieving defect list, got null pointer</p>");
			out.println("</body>");
			out.println("</html>");	*/

			nextPage = "status.jsp";
			request.setAttribute("msgType", "error");
			request.setAttribute("message", "Error loading defect list from database for the home page.");

		} else {
			// If all is OK, the next page to be displayed is the homepage (defect list).
			nextPage = "defectlist.jsp";
			// Add the defect list to the request.
			request.setAttribute("defectList", defectList);
		}

		// Forward the request to the appropriate page or servlet, as determined above.
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doPost(request, response);
	}
}
